# -*- coding: UTF-8 -*-

from datetime import datetime
import sys
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct, DECIMAL
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger



__all__ = ['MonitorDorisHttpRecord']

class MonitorDorisHttpRecord(Base, SessionMixin):
    '''
    接口调用记录表
    '''
    __tablename__ = "monitor_doris_http_record"
    domain = Column(String(64), nullable=False, index=True, comment='接口域名')
    url = Column(String(256), nullable=False, index=True, comment='接口url')
    method = Column(String(32), nullable=False, index=True, comment='接口方法')
    provider = Column(String(32), nullable=False, index=True, comment='服务提供者')
    production = Column(String(32), nullable=False, index=True, comment='所属产品')
    total = Column(Integer, nullable=True, default=0, index=True, comment='所有状态码的数量')
    status2xx = Column(Integer, nullable=True, default=0, index=True, comment='200状态码的数量')
    status2xx_req_avg = Column(DECIMAL(10,2), nullable=True, default=0, comment='200状态码的平均请求时间')
    status2xx_resp_avg = Column(DECIMAL(10,2), nullable=True, default=0, comment='200状态码的平均请求时间')
    status3xx = Column(Integer, nullable=True, default=0, index=True, comment='300状态码的数量')
    status3xx_req_avg = Column(DECIMAL(10,2), nullable=True, default=0, comment='300状态码的平均请求时间')
    status3xx_resp_avg = Column(DECIMAL(10,2), nullable=True, default=0, comment='300状态码的平均请求时间')
    status4xx = Column(Integer, nullable=True, default=0, index=True, comment='400状态码的数量')
    status4xx_req_avg = Column(DECIMAL(10,2), nullable=True, default=0, comment='400状态码的平均请求时间')
    status4xx_resp_avg = Column(DECIMAL(10,2), nullable=True, default=0, comment='400状态码的平均请求时间')
    status5xx = Column(Integer, nullable=True, default=0, index=True, comment='500状态码的数量')
    status5xx_req_avg = Column(DECIMAL(10,2), nullable=True, default=0, comment='500状态码的平均请求时间')
    status5xx_resp_avg = Column(DECIMAL(10,2), nullable=True, default=0, comment='500状态码的平均请求时间')
    begin_time = Column(DateTime, nullable=False, index=True, comment="统计开始时间")
    end_time = Column(DateTime, nullable=False, index=True, comment="统计结束时间")
    update_at = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    comment = Column(String(256), nullable=False, comment='接口说明')


    __table_args__ = (
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic',
        }
    )

    def __repr__(self):
        return f"<monitor_doris_url_record='{self.url}'>"


    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }

        return result



    @classmethod
    def get_object_info_for_time(cls, db: Session, begin, end):
        """
        获取指定时间段的http接口状态记录
        """
        object_info = db.query(cls).filter(and_(
            cls.update_at >= begin,
            cls.update_at <= end)
        ).order_by(cls.update_at.desc()).to_dict()
        return object_info